package com.feign.feignClient.coder;

import com.alibaba.fastjson.JSONObject;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;

import java.lang.reflect.Type;

/**
 * 平安银行支付特定的Encoder
 */
public class JsonEncoder implements Encoder {

    @Override
    public void encode(Object o, Type type, RequestTemplate requestTemplate) throws EncodeException {
        //若是字符串对象，直接请求
        if(o instanceof  String){
            requestTemplate.body((String) o);
        }else {
            //转化为JSONObject（Map对象），利用Map对象优势进行对每个字段进行拼接字符串
            JSONObject requestData =  JSONObject.parseObject(JSONObject.toJSONString(o));
            StringBuilder bodyBuild = new StringBuilder();
            //拼接请求字符串
            requestData.keySet().forEach(key-> bodyBuild.append(key).append("=").append( requestData.get(key) ).append("&"));
            //将对象序列化，并设置到请求体的body
            requestTemplate.body( bodyBuild.toString()  );
        }
        //进行请求
        requestTemplate.request();
    }

}
